package com.mr.base.alpha.config;

import com.github.pagehelper.PageInterceptor;
import com.mr.base.core.mybatis.TenantInterceptor;
import com.mr.base.core.mybatis.handler.TenantLineHandler;
import com.mr.platform.permission.thread.AccountThreadLocal;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Component
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.mr.base.alpha.mappers.**", "com.mr.marketing.alpha.mappers.expand.*" })
@Slf4j
public class MysqlDataSource {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {

        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        // 分页插件
        PageInterceptor pageHelper = new PageInterceptor();
        Properties props = new Properties();
        props.setProperty("helperDialect", "mysql");
        props.setProperty("offsetAsPageNum", "false");
        props.setProperty("rowBoundsWithCount", "false");
        props.setProperty("pageSizeZero", "false");

        props.setProperty("reasonable", "false");
        props.setProperty("supportMethodsArguments", "false");
        props.setProperty("returnPageInfo", "none");
        pageHelper.setProperties(props);

        TenantInterceptor tenant = new TenantInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                return new LongValue(AccountThreadLocal.getAccountVO().getTenantId());
            }
        });

        // 添加插件
        sessionFactory.setPlugins(new Interceptor[] {
                tenant
                ,pageHelper
        });

        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);

        return sessionFactory.getObject();
    }

    @Bean
    public SqlSessionTemplate amonSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
